package com.gsoe.auth.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gsoe.auth.mapper.UserRankingMapper;
import com.gsoe.auth.po.UserRanking;
import com.gsoe.auth.vo.RankingVO;
import com.gsoe.auth.service.UserInfoService;
import com.gsoe.auth.service.UserRankingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserRankingServiceImpl extends ServiceImpl<UserRankingMapper, UserRanking> implements UserRankingService {
    @Autowired
    UserInfoService userInfoService;

    public RankingVO getRanking(Long id) {
        RankingVO rankingVO = new RankingVO();
        List<UserRanking> rankingList = list();
        Map<Long, List<UserRanking>> groupById = rankingList.stream().collect(Collectors.groupingBy(UserRanking::getUserId));
        List<UserRanking> userRankingList=new ArrayList<>();
        groupById.forEach((k, v) -> {
            //根据创建日期排序
            v.sort((r1, r2) -> {
                LocalDateTime createTimeR1 = r1.getCreateTime();
                LocalDateTime createTimeR2 = r2.getCreateTime();
                if (createTimeR1 == null) return 1;
                if (createTimeR2 == null) return -1;
                return createTimeR1.compareTo(createTimeR2);
            });
            //将最后一次创建结果加入到集合
            userRankingList.add(v.get(v.size()-1));
        });
        //将每个用户按最后一次得分排序
        userRankingList.sort(Comparator.comparing(UserRanking::getRanking).reversed());


        List<UserRanking> loginUserRankingList = groupById.get(id);
        //该用户的分值变化情况
        rankingVO.setLoginUserRankingList(loginUserRankingList);
        //用户数量
        rankingVO.setTotalUser(userInfoService.count());
        if(CollectionUtil.isNotEmpty(loginUserRankingList)){
            //该用户得分
            rankingVO.setRankingScore(loginUserRankingList.get(loginUserRankingList.size()-1).getRanking());
            //该用户的排名
            for (int i = 1; i <= userRankingList.size(); i++) {
                if(Objects.equals(userRankingList.get(i-1).getUserId(), id)){
                    rankingVO.setRanking(i);
                    break;
                }
            }
        }else{
            rankingVO.setRankingScore(1000);
            rankingVO.setRanking(-1);
            List<UserRanking> list=new ArrayList<>();
            list.add(new UserRanking(null, id, 1000, LocalDateTime.now()));
            rankingVO.setLoginUserRankingList(list);
        }


        //该所有用户的得分情况
        rankingVO.setAllUserRankingList(userRankingList);

        return rankingVO;
    }
}
